<template>
  <n-card title="文件列表" class="max-w-2xl mx-auto mt-10">
    <n-space vertical>
      <n-button type="primary" @click="fetchFiles" :loading="loading"> 刷新文件列表 </n-button>

      <n-spin :show="loading">
        <n-tree
          v-if="treeData.length > 0"
          :data="treeData"
          block-line
          :default-expand-all="true"
          :render-label="renderLabel"
        />
        <n-empty v-else description="暂无文件" />
      </n-spin>
    </n-space>
  </n-card>

  <ResultsList v-if="results.length" :results="results" />
</template>

<script setup>
import { NCard, NButton, NTree, NTag, NSpace, NSpin, NEmpty } from 'naive-ui'
import { h } from 'vue'
import { ref, onMounted } from 'vue'

import service from '@/network'

import ResultsList from '@/components/resultsList/index.vue'

const loading = ref(false)
const treeData = ref([])

const results = ref([])

// 文件扩展名 -> 中文映射
const extMap = {
  cfg: 'CFG 文件',
  dat: 'DAT 文件',
  dmf: 'DMF 文件',
  hdr: 'HDR 文件',
  inf: 'INF 文件',
}

// 页面加载时获取文件列表
onMounted(() => {
  fetchFiles()
})

// 请求文件列表
const fetchFiles = async () => {
  loading.value = true
  try {
    const res = await service.get('/files-list')
    // 注意：假设后端返回 { "data": ["a.cfg", "a.dat", ...] }
    const files = res.data || []
    treeData.value = buildTree(files)
  } catch (err) {
    console.error('获取文件列表失败', err)
  } finally {
    loading.value = false
  }
}

// 按基础文件名分组并构造 Naive UI Tree 数据结构
const buildTree = (fileList) => {
  const groups = {}
  fileList.forEach((filename) => {
    const parts = filename.split('.')
    if (parts.length < 2) return
    const base = parts.slice(0, -1).join('.')
    const ext = parts.pop().toLowerCase()
    const display = extMap[ext] || `未知类型 (${ext})`

    if (!groups[base]) groups[base] = []
    groups[base].push({
      key: `${base}-${ext}`,
      label: display,
    })
  })

  // 转换成树结构
  return Object.entries(groups).map(([base, children]) => ({
    key: base,
    label: base,
    children,
  }))
}

// 渲染标签 — 为组节点添加操作按钮
const renderLabel = ({ option }) => {
  if (option.children) {
    // 文件组节点
    return h(
      'div',
      {
        style: {
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          width: '100%',
        },
      },
      [
        h('strong', { style: { flex: 1 } }, option.label),
        h('div', { style: { display: 'flex', gap: '8px' } }, [
          h(
            NButton,
            {
              size: 'tiny',
              type: 'primary',
              tertiary: true,
              onClick: (e) => analyze(e, option.label),
            },
            () => h('span', '故障分析'),
          ),
        ]),
      ],
    )
  } else {
    // 子文件节点
    return h(NTag, { size: 'small', type: 'info' }, { default: () => option.label })
  }
}

const analyze = (e, base) => {
  e.stopPropagation()
  console.log('分析文件组:', base)
  service
    .get('/fault-analyze', { params: { file_name: base } })
    .then((response) => {
      console.log(response.data)
      results.value = response.data || []
    })
    .catch((err) => {
      console.error('分析请求失败', err)
    })
}
</script>

<style scoped>
.max-w-2xl {
  max-width: 600px;
}
.mx-auto {
  margin-left: auto;
  margin-right: auto;
}
.mt-10 {
  margin-top: 2.5rem;
}
</style>
